package com.coding.service.impl;

import com.coding.base.pojo.BaseModel;
import com.coding.dao.QuestionDao;
import com.coding.pojo.Question;
import com.coding.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @auther wangchenghao
 * @date 2020/10/2
 **/
@Service
public class QuestionImpl implements QuestionService {
    @Autowired
    QuestionDao questionDao;

    @Override
    public void queryAllList(BaseModel model) throws Exception {
        List<Question> questionList = questionDao.queryAll();
        if (questionList == null) {
            model.setFailure("未查询到题目");
        } else {
            questionList=getSubStringByRadom(questionList,5);
            model.setSucceed("随意抽取五道题", questionList);
        }
    }

    @Override
    public void selectById(int question_id, BaseModel baseModel) throws Exception {
        Question question = questionDao.selectByPrimaryKey(question_id);
        if (question == null) {
            baseModel.setFailure("未查询到题目");
        } else {
            baseModel.setSucceed("查询到题目", question);
        }
    }
    public List<Question> getSubStringByRadom(List<Question> list, int count){
        List backList = null;
        backList = new ArrayList<Question>();
        Random random = new Random();
        int backSum = 0;
        if (list.size() >= count) {
            backSum = count;
        }else {
            backSum = list.size();
        }
        for (int i = 0; i < backSum; i++) {
//			随机数的范围为0-list.size()-1
            int target = random.nextInt(list.size());
            backList.add(list.get(target));
            list.remove(target);
        }
        return backList;
    }
}
